package com.hydra.framework.thread;

import android.os.Looper;
import androidx.annotation.NonNull;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

public class ThreadBus {

    private static AtomicInteger BusThreadBegin = new AtomicInteger(0);

    private static int gen() {
        return BusThreadBegin.incrementAndGet();
    }

    private static ConcurrentHashMap<Integer, ThreadAsyncAdapter> bus = new ConcurrentHashMap<>();

    public static final int Sync = 0;

    //主线程只有一个
    public static final int Main = 1;

    public static final int Working = 2;
    public static final int IO = 3;
    public static final int Net = 4;
    public static final int Db = 5;
    public static final int Bind = 6;
    public static final int Shit = 7;
    public static final int Pool = 8;

    static {
        addThread(new HandlerThreadAsyncAdapter(Looper.getMainLooper()));
        addThread(new HandlerThreadAsyncAdapter("Working"));
        addThread(new HandlerThreadAsyncAdapter("IO"));
        addThread(new HandlerThreadAsyncAdapter("Net"));
        addThread(new HandlerThreadAsyncAdapter("Db"));
        addThread(new HandlerThreadAsyncAdapter("Bind"));
        addThread(new HandlerThreadAsyncAdapter("Shit"));
        addThread(new ScheduledThreadPoolAsyncAdapter(10));
    }

    /**
     * 可自定义添加配置
     */
    public static int addThread(@NonNull ThreadAsyncAdapter threadAsyncAdapter) {
        int id = gen();

        bus.put(id, threadAsyncAdapter);

        return id;
    }

    public static ThreadAsyncAdapter threadAdapter(int idx) {
        return bus.get(idx);
    }

    public static boolean post(int idx, Runnable r) {
        return threadAdapter(idx).post(r);
    }

    public static boolean postDelayed(int idx, Runnable r, long delayMillis) {
        return threadAdapter(idx).postDelayed(r, delayMillis);
    }

    public static boolean postAtTime(int idx, Runnable r, long uptimeMillis) {
        return threadAdapter(idx).postAtTime(r, uptimeMillis);
    }

    public static void removeCallbacks(int idx, Runnable r, Object token) {
        threadAdapter(idx).removeCallbacks(r, token);
    }

    public static boolean callThreadSafe(int idx, Runnable r) {
        ThreadAsyncAdapter adapter = threadAdapter(idx);
        if (adapter != null) {
            if (adapter.isCurrentThread()) {
                r.run();
            } else {
                adapter.post(r);
            }
            return true;
        }
        return false;
    }

    public static void quitAndRemove(int idx) {
        ThreadAsyncAdapter adapter = bus.remove(idx);

        if(adapter != null) {
            adapter.quit();
        }
    }
}
